/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package queenb.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import queenb.net.entitybean.Login;
import queenb.web.session.EnvironmentSession;
import queenb.web.session.KapiMenu;
import queenb.web.session.LoginSession;
import queenb.web.session.PageController;
import queenb.web.util.BundleFinder;
import queenb.web.util.SessionProvider;
import queenb.web.util.Util;

/**
 *
 * @author thanhct
 */
public class QueenbController {

    private static final Logger logger = Logger.getLogger(QueenbController.class);
    public LoginSession loginSession;
    private BundleFinder bundleFinder;
    private EnvironmentSession environmentSession;
    protected final String ACTION_NEW = "new";
    protected final String ACTION_UPDATE = "update";
    protected final String ACTION_DELETE = "delete";
    public KapiMenu kapiMenu;
    private PageController page;
    private static String requestStringUrl;

    public QueenbController() {
      //  Object page = getPage();
      
        try {
            if (getRequest().getPathInfo() != null) {
                
                if (!getRequest().getPathInfo().equals("/index/globalreport.jsp")) {
                    requestStringUrl = getRequest().getQueryString();

                }
                if (getLogin() != null && getLogin().getUserName() != null) {
                     loginSession.getLogin().setShowGlobalMessage(false);
                    if (getRequest().getPathInfo().equals("/index/login.jsp")) {
                        sendRedirect("customerexpand.jsp");
                    }
                } else {
//                    System.out.println("---------------queenb controller ----------");
//                    ExternalContext ext = FacesContext.getCurrentInstance().getExternalContext();
//                    HttpSession session = (HttpSession) ext.getSession(true);
//                    session.invalidate();
//                    ext.getSessionMap().clear();
//                    showGlobalReport(true, "TAI KHOAN BI CHIEM DUNG");
                    removeSession();
                    sendRedirect("login.jsp"+Util.convertMD5("/index/login.jsp")+".jsp");
                }

            }
        } catch (Exception ex) {
        }
    
    }

    public void removeSession() {
        SessionProvider.removeSessionMapValue("companyID");
        SessionProvider.removeSessionMapValue("depID");
        SessionProvider.removeSessionMapValue("groupID");
    }

    protected void showMessageIfNeed() {
        Object sms = getRequest().getParameter("sms");
        if (sms != null && !sms.toString().equals("")) {
            showPopupMessage(sms.toString(), "ABACUS INFO");
        }
    }

    protected void setMessages(String message, String detailMessage) {
        getContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, detailMessage));
    }

    protected Login getLogin() {
        return getLoginSession().getLogin();
    }

    protected FacesContext getCurrentFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    public FacesContext getContext() {
        return FacesContext.getCurrentInstance();
    }

    public ExternalContext getExContext() {
        return getContext().getExternalContext();
    }

    public HttpServletRequest getRequest() {
        return (HttpServletRequest) getExContext().getRequest();
    }

    public HttpServletResponse getResponse() {
        return (HttpServletResponse) getExContext().getResponse();
    }

    protected void showPopupMessage(String sms, String title) {
        try {
//            <script language='javascript' type='text/script'>" + sms + "</script>"
            getResponse().getWriter().write(
                    "<div id='dialog' title='" + title + "'>"
                    + "<p>" + sms + "</p>"
                    + "</div>");
        } catch (IOException ex) {
            logger.debug("could not write message");
        }
    }

    protected void showAlertMessage(String sms) {
        try {
            getResponse().getWriter().write(
                    "<script language='javascript' type='text/html'>alert(" + sms + ")</script>");
        } catch (IOException ex) {
            logger.debug("could not write message");
        }
    }

    public void sendRedirect(String url) {
        try {
            url = getExContext().encodeResourceURL(url);
            getResponse().sendRedirect(url + "?linkhref=" + Util.convertMD5(getRequest().getRequestURI()));
            getContext().responseComplete();
        } catch (IOException ex) {
            logger.debug("Error: Could not send redirect:" + ex.getMessage());
            setMessages("ERR:SENDREDIRECT:CONLL:cound not send page", "detail:" + ex.getMessage());
        }
    }

    public void sendRedirectUrlTab(String url) {
        try {
            url = getExContext().encodeResourceURL(url);
            
            getResponse().sendRedirect(url);
            getContext().responseComplete();
        } catch (IOException ex) {
            logger.debug("Error: Could not send redirect:" + ex.getMessage());
            setMessages("ERR:SENDREDIRECT:CONLL:cound not send page", "detail:" + ex.getMessage());
        }
    }

    public void sendRedirectExcel(String url) {
        try {

            //getResponse().setContentType("application/force-download");
            getResponse().setContentType("application/vnd.ms-excel");
            //getResponse().setContentType("application/msexcel");
            getResponse().setHeader("Content-Disposition", "inline;filename=report.xls");
            getResponse().setHeader("Pragma", "public");
            getResponse().setHeader("Expires", "0");
            getResponse().setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            //getResponse().setHeader("Content-type", "application-download");
            getResponse().setHeader("Content-Transfer-Encoding", "binary");
            File file = new File(url);
            FileInputStream fileIn = new FileInputStream(file);
            ServletOutputStream out = getResponse().getOutputStream();

            byte[] outputByte = new byte[4096];
            //copy binary contect to output stream
            while (fileIn.read(outputByte, 0, 4096) != -1) {
                out.write(outputByte, 0, 4096);
            }
            fileIn.close();
            out.close();

            getContext().responseComplete();
        } catch (IOException ex) {
            logger.debug("Error: Could not send redirect:" + ex.getMessage());
            setMessages("ERR:SENDREDIRECT:CONLL:cound not send page", "detail:" + ex.getMessage());
        }
    }

    public void sendRedirectURL(String file, int id, int tabnum) {
        long lDateTime = new Date().getTime();
        sendRedirectUrlTab(file + "?linkSGT=" + Util.convertMD5(getRequest().getRequestURI()) + "&tab=tab" + tabnum + id + "&flag=" + lDateTime + "&#" + id);
    }
    
     public void sendRedirectURLnew(String file,String tabnum,int id) {
        long lDateTime = new Date().getTime();
        sendRedirectUrlTab(file + "?tab=" + tabnum +id+ "&flag=" + lDateTime +  "?linkSGT=" + Util.convertMD5(getRequest().getRequestURI()));
    }

    /**
     * @return the loginSession
     */
    public LoginSession getLoginSession() {
        loginSession = (LoginSession) SessionProvider.getSession("loginSession", FacesContext.getCurrentInstance());
        if (loginSession == null) {
            loginSession = new LoginSession();
        }
        return loginSession;
    }

    private boolean isLogged() {
        return getLoginSession().isLogged();
    }

    /**
     * @return the bundleFinder
     */
    public BundleFinder getBundleFinder() {
//        Locale locale = getContext().getViewRoot().getLocale();
        Locale locale = getEnvironmentSession().getCurrentLocale();
        String bundleName = FacesContext.getCurrentInstance().getApplication().getMessageBundle();
        logger.debug("Current Bundle name:" + bundleName);
        bundleFinder = BundleFinder.getInstance(locale, bundleName);
        return bundleFinder;
    }

    protected String getResourceString(String key, Object[] params) {
        try {
            Locale locale = getEnvironmentSession().getCurrentLocale();
            getBundleFinder().setLocale(locale);
            logger.debug("current locale:" + getBundleFinder().getLocale().toString() + " current key:" + key);
            return getBundleFinder().getLocaleResources(key, params);
        } catch (Exception ex) {
            return null;
        }
    }

    protected String getResourceString(String key) {
        Locale locale = getEnvironmentSession().getCurrentLocale();
        getBundleFinder().setLocale(locale);
        logger.debug("current locale:" + getBundleFinder().getLocale().toString() + " current key:" + key);
        return getBundleFinder().getLocaleResources(key);
    }

    public String getResourceStringExtend(String key) {
        Locale locale = getEnvironmentSession().getCurrentLocale();
        getBundleFinder().setLocale(locale);
        logger.debug("current locale:" + getBundleFinder().getLocale().toString() + " current key:" + key);
        return getBundleFinder().getLocaleResources(key);
    }

    /**
     * @param bundleFinder the bundleFinder to set
     */
    public void setBundleFinder(BundleFinder bundleFinder) {
        this.bundleFinder = bundleFinder;
    }

    public void showGlobalReport(boolean show, String reportMessage) {
        try {
            Login login = getLogin();
            System.out.println("-----------show repot=="+show);
            login.setShowGlobalMessage(show);
            login.setGlobalMessage(reportMessage);
        } catch (Exception ex) {
        }
    }

    /**
     * @return the environmentSession
     */
    public EnvironmentSession getEnvironmentSession() {
        environmentSession = (EnvironmentSession) SessionProvider.getSession("environmentSession", getContext());
        return environmentSession;
    }

    /**
     * @param environmentSession the environmentSession to set
     */
    public void setEnvironmentSession(EnvironmentSession environmentSession) {
        this.environmentSession = environmentSession;
    }

    /**
     * @return the kapiMenu
     */
    public KapiMenu getKapiMenu() {
        kapiMenu = (KapiMenu) SessionProvider.getSession("kapiMenu", FacesContext.getCurrentInstance());
        if (kapiMenu == null) {
            kapiMenu = new KapiMenu();
        }
        return kapiMenu;
    }

    /**
     * @param kapiMenu the kapiMenu to set
     */
    public void setKapiMenu(KapiMenu kapiMenu) {
        this.kapiMenu = kapiMenu;
    }

    /**
     * @return the page
     */
//    public PageController getPage() {
//        page = (PageController) SessionProvider.getSession("pageController", FacesContext.getCurrentInstance());
//        if (page == null) {
//            page = new PageController();
//        }
//        return page;
//    }
//
//    /**
//     * @param page the page to set
//     */
//    public void setPage(PageController page) {
//        this.page = page;
//    }
}
